package android.textIt.frontend.broadcast;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.textIt.R;
import android.textIt.backend.dao.*;
import android.textIt.backend.model.*;
import android.textIt.frontend.activity.MainActivity;
import android.textIt.util.TextItUtil;
import android.util.Log;

public class SMSReceiver extends BroadcastReceiver {
  private final static  String DEBUG_TAG = "TextIt SMSReceiver";
	private static final int MSG_RECEIVED_ID = 1;
	
  private static UserDao userDAO;
  private static GroupDao groupDAO;
  private static MessageDao messageDAO;

	
  @Override
  public void onReceive(Context context, Intent intent) 
  {
    //---get the SMS message passed in---
    Bundle bundle = intent.getExtras();        
    SmsMessage[] msgs = null;
    String phoneNo = null;
    String message = null;
    User sender = null;
    userDAO = new UserDao(context);
    groupDAO = new GroupDao(context);
    messageDAO = new MessageDao(context);
    
    if (bundle != null)
    {
  		// if owner is not created yet, no need to process further
  		User owner = userDAO.getUserbyID(1);
  		if (owner == null){
  			return;
  		}
  		
      //---retrieve the SMS message received---
      Object[] pdus = (Object[]) bundle.get("pdus");
      msgs = new SmsMessage[pdus.length];            
      for (int i=0; i<msgs.length; i++){
          msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
          phoneNo = msgs[i].getOriginatingAddress();  
          message = msgs[i].getMessageBody().toString();
      }
      
      if ((phoneNo != null) && (message != null)){
      	sender = userDAO.findUserByNumber(Long.parseLong(phoneNo));
      	if (sender == null){ // user does not exist in our system, so create
      		sender = new User();
      		sender.setName(phoneNo); // we don't know the user, so set the name to phone no
      		sender.setIsTextItUser(0); // set as not textit user by default
      		sender.setPhone(Long.parseLong(phoneNo));
      		userDAO.createUser(sender);
      	}
      	
      	sender = userDAO.findUserByNumber(Long.parseLong(phoneNo));
      	if (sender != null){ // shouldn't be null at this point, but check just in case something fails in dao
      		Message m = new Message();
      		Status s = new Status(1, "unread");
      		m.setContent(message);
      		m.setSender(sender);
      		m.setReceiver(groupDAO.getGroupById(sender.getiGroup()));
      		m.setStatus(s);
      		m.setReference_id(-1);
      		messageDAO.createMessage(m);
      		
          NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
          
          int icon = R.drawable.sms;
          CharSequence tickerText = "TextIt";
          long when = System.currentTimeMillis();
          CharSequence contentTitle = sender.getName();
          CharSequence contentText = message;
          Intent notificationIntent = new Intent(); // new intent
          notificationIntent.setAction("ViewMessages");
          String iGroup = String.valueOf(sender.getiGroup());
          Log.v(DEBUG_TAG, "sender igroup: " + iGroup);
	        notificationIntent.putExtra( "id", iGroup); 
	        notificationIntent.putExtra("to", TextItUtil.TO_INDIVIDUAL);

          PendingIntent contentIntent = PendingIntent.getActivity(context, 1, notificationIntent, 0);
          
          Notification notification = new Notification(icon, tickerText, when);
          notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
          notification.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL;
          mNotificationManager.notify(MSG_RECEIVED_ID, notification);
      	}          	
      }
    }                         
  }
}
